package grouplife::Controller::Root;
use Moose;
use Encode;
use namespace::autoclean;
use Data::Dumper;
use Digest::MD5;
use Crypt::CBC;
use grouplife::Model::Users::UsersSearchModel;
use grouplife::Model::Store::StoreSearchModel;
use grouplife::Model::Tuan::TuansSearchModel;
use grouplife::Model::UserStore::UserStoreModel;
use grouplife::Model::Leimu::LeimuModel;
use grouplife::Model::Category::CategoryModel;
use grouplife::Model::CategoryStore::CategoryStoreModel;
use grouplife::Model::CategoryTuan::CategoryTuanModel;
use grouplife::Model::University::UniversityModel;
use grouplife::Model::UserTuanStores::UserTuanStoresModel;
use grouplife::Model::Topic::TopicSearchModel;
use Date::Parse;

BEGIN { extends 'Catalyst::Controller' }

#
# Sets the actions in this controller to be registered with no prefix
# so they function identically to actions created in MyApp.pm
#
__PACKAGE__->config(namespace => '');
__PACKAGE__->config( 'Plugin::ConfigLoader' => { file => 'grouplife.yml' } );

=head1 NAME

grouplife::Controller::Root - Root Controller for grouplife

=head1 DESCRIPTION

[enter your description here]

=head1 METHODS

=head2 index

The root page (/)

=cut

sub find_password:Local {
	my ( $self, $c ) = @_;
	
	$c->stash(css   => 'denglu.css');
	$c->stash(template => 'find_passwd.tt2');
}
sub find_password_do:Local {
	my ( $self, $c ) = @_;
	my $email = $c->request->params->{"email"}  || '0';
	
	$email =~ s/^\s+//;
	$email =~ s/\s+$//;

	if($email eq '0' or $email eq "") {
		$c->stash(error_msg => "请输入您的邮箱");
	} else {
		my @users = $c->model('Users::UsersSearchModel')->get_user_by_email($email);
		my $count = scalar(@users);
		my $user = $users[0];
		if($count == 0) {
			$c->stash(error_msg => "该邮箱尚未注册");
		} else {
			#TODO
			my $crypt_key = $c->config->{crypt_key};
			my $crypt_iv = $c->config->{crypt_iv};
			my $cipher = Crypt::CBC->new( -key => "$crypt_key",
					-cipher => 'Blowfish',
					-blocksize =>  8,
					-header => 'none',
					-iv => "$crypt_iv" 
					);
			my $ciphertext = $cipher->encrypt_hex($user->email_address);
			my $conf_url = $c->config->{reset_passwd_url} . "?code=" . $ciphertext;
			my (%params, %options);
			$options{INCLUDE_PATH} = $c->config->{email_template_path};
			$params{username} = $user->username;
			$params{email}  = $user->email_address;
			$params{conf_url} = $conf_url;

			my $title = "拼单族重置密码邮件";
			my $sender = Util::Email::SendEmail->new();
			my $template = "email/reset_passwd.html.tt";
			$sender->send($email, $title, $template, \%params, \%options);
			$c->stash(css   => 'zhuce.css');
			$c->stash(template => 'users/reset_passwd_success.tt2');
			return;
		}
	}
	$c->stash(css   => 'denglu.css');
        $c->stash(title => '重置密码');
	$c->stash(template => 'find_passwd.tt2');
}

sub reset_password:Local {
	my ( $self, $c ) = @_;
	my $code = $c->request->params->{"code"};
	my $crypt_key = $c->config->{crypt_key};
	my $crypt_iv = $c->config->{crypt_iv};
	my $cipher = Crypt::CBC->new( -key => "$crypt_key",
			-cipher => 'Blowfish',
			-blocksize =>  8,
			-header => 'none',
			-iv => "$crypt_iv" 
			);
	my $email = $cipher->decrypt_hex($code);
	my @users = $c->model('Users::UsersSearchModel')->get_user_by_email($email);
	my $count = scalar(@users);
	my $user = $users[0];
	unless($count == 0) {
		$c->stash(css   => 'denglu.css');
		$c->stash(title => '设置新密码');
		$c->stash(javascript => '/user/reset_password.js');
		$c->stash(code => $code);
		$c->stash(user_id => $user->id);
		$c->stash(template => 'users/reset_passwd_form.tt2');
		return;
	}
	
	$c->stash(css   => 'zhuce.css');
        $c->stash(title => '重置密码失败');
	$c->stash(template => 'users/reset_passwd_failed.tt2');
}

sub reset_password_do:Local {
	my ( $self, $c ) = @_;
	my $create_password= $c->request->params->{"create_password"}  || '0';
	my $repeat_password= $c->request->params->{"repeat_password"}  || '0';
	my $user_id = $c->request->params->{"user_id"} || '0';
	my $code = $c->request->params->{"code"} || '0';
	
	if($create_password eq '0') {
		$c->stash(error_msg => "请输入您的新密码");
	} elsif( $repeat_password eq '0') {
		$c->stash(error_msg => "请再次输入您的新密码");
	} elsif( $create_password ne $repeat_password) {
		$c->stash(error_msg => "两次输入密码不一致");
	} elsif( $user_id eq '0') {
		$c->stash(css   => 'zhuce.css');
		$c->stash(title => '重置密码失败');
		$c->stash(template => 'users/reset_passwd_failed.tt2');
		return;	
	} elsif( $code eq '0') {
		$c->stash(css   => 'zhuce.css');
		$c->stash(title => '重置密码失败');
		$c->stash(template => 'users/reset_passwd_failed.tt2');
		return;	
	} else {
		my $user = $c->model('Users::UsersSearchModel')->find($user_id);
		$user->update({password => $create_password});
		$c->response->redirect($c->uri_for("/login"));
	}
	$c->stash(css   => 'denglu.css');
	$c->stash(user_id => $user_id);
	$c->stash(code   => $code);
	$c->stash(title => '设置新的密码');
	$c->stash(template => 'users/reset_passwd_form.tt2');
}

sub register_verification:Local {
	my ( $self, $c ) = @_;
	my $uid = $c->request->params->{"uid"}  || '';
	my $code = $c->request->params->{"code"}  || '';
	
	my $user = $c->model('Users::UsersSearchModel')->find($uid);
	if ($user and $user->active ne 'Y') {
		my $md5 = Digest::MD5->new;
		$md5->add($user->email_address);
		if ($md5->hexdigest eq $code) {
			$user->update({active => 'Y'});
			$c->stash(css   => 'zhuce.css');
			$c->stash(template => 'users/confirm_success.tt2');
			return;
		} 
	}
	my $message = "";
	unless($user) {
		$message = "该验证连接已经失效";
	}
	if($user and $user->active eq 'Y') {
		$message = "您已经验证过此信息";
	}
	$c->stash(css   => 'zhuce.css');
	$c->stash(message   => $message);
	$c->stash(template => 'users/confirm_failed.tt2');
}
sub taobao_bind_verification:Local {
	my ( $self, $c ) = @_;
	my $source = $c->request->params->{"source"}  || '';
	my $source_nick = $c->request->params->{"source_nick"}  || '';
	my $email = $c->request->params->{"email"}  || '';
	my $code = $c->request->params->{"code"}  || '';
	$source_nick= encode_utf8(decode("gbk",$source_nick));
	
	my $md5 = Digest::MD5->new;
	$md5->add($email);
	$md5->add($source_nick);
	if ($md5->hexdigest eq $code) {
		my @source_nicks = $c->model('Users::UsersSearchModel')->get_user_by_nick($source, $source_nick);
		unless(defined $source_nicks[0]) {
			my @users = $c->model('Users::UsersSearchModel')->get_user_by_email($email);
			my $user = $users[0];
			my @source_nick = $user->source_nick;
			foreach(@source_nick) {
				$_->delete() if($_->source_id eq $source);
			}

			$user->add_to_source_nick({
				source_id => $source,
				source_nick => $source_nick
			});
			$c->stash(title => '账号绑定成功');
			$c->stash(css   => 'zhuce.css');
			$c->stash(template => 'taobao/bind_confirm_success.tt2');
		} else {
			$c->stash(title => '账号绑定失败');
			$c->stash(css   => 'zhuce.css');
			$c->stash(template => 'taobao/bind_duplicate.tt2');
		}
	} else {
		$c->stash(title => '账号绑定失败');
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'taobao/bind_confirm_failure.tt2');
	}
}

sub qq_bind_verification:Local {
	my ( $self, $c ) = @_;
	my $source_nick = $c->request->params->{"source_nick"}  || '';
	my $user_id = $c->request->params->{"user_id"}  || '';
	my $email = $c->request->params->{"email_address"}  || '';
	my $code = $c->request->params->{"code"}  || '';
	
	my $md5 = Digest::MD5->new;
	$md5->add($email);
	$md5->add($source_nick);
	if ($md5->hexdigest eq $code) {
		my @binds = $c->model('QQBind::QQBindModel')->get_bind($user_id);
		if(defined $binds[0]) {
			$binds[0]->update({status => 'Y'});
			my $auth_user = $c->find_user({ id => $user_id });
                	$c->set_authenticated($auth_user);
                	$c->session->{login_user} = $auth_user;
			$c->stash(css   => 'zhuce.css');
			$c->stash(title => '账号绑定成功');
			$c->stash(template => 'taobao/bind_confirm_success.tt2');
		} else {
			$c->stash(css   => 'zhuce.css');
			$c->stash(title => '账号绑定失败');
			$c->stash(template => 'taobao/bind_confirm_failure.tt2');
		}
	} else {
		$c->stash(title => '账号绑定失败');
		$c->stash(css   => 'zhuce.css');
		$c->stash(template => 'taobao/bind_confirm_failure.tt2');
	}
}
#select tuan_id, count(distinct user_id) as user_count from user_tuan group by tuan_id order by user_count DESC
sub index :Path :Args(0) {
	my ( $self, $c ) = @_;

	$c->cache_page( $c->config->{time_out} );
	my $universities_list1 = $c->model('University::UniversityModel')->get_all_univs();
	my $universities_list2 = $c->model('University::UniversityModel')->get_all_offices();
	my $stores_total = $c->model('Store::StoreSearchModel')->store_total('', 0);
	my $tuan_total = $c->model('Tuan::TuanSearchModel')->get_total_tuan_number_no_args();
        if($c->session->{login_user}) {
                my $university_id = $c->session->{login_user}->university_id;
                my $office_id = $c->session->{login_user}->office_id;
                my $house_id = $c->session->{login_user}->house_id;
                my $ongoings = $c->model('Tuan::TuansSearchModel')->find_ongoing_tuans_for_university($university_id);
                my $house_ongoings = $c->model('Tuan::TuansSearchModel')->find_ongoing_tuans_for_university($house_id);
                my $office_ongoings = $c->model('Tuan::TuansSearchModel')->find_ongoing_tuans_for_university($office_id);
                $c->stash(ongoing_count => scalar(@$ongoings));
                $c->stash(office_ongoing_count => scalar(@$office_ongoings));
                $c->stash(house_ongoing_count => scalar(@$house_ongoings));
                $c->stash(user => $c->model('Users::UsersSearchModel')->find($c->session->{login_user}->id));
               
        }
	my $taobao_oauth_url = $c->config->{taobao_oauth_url};
        my $redirect_uri = $c->config->{redirect_uri};
        my $response_type = $c->config->{response_type};
        my $scope = $c->config->{scope};
        my $view = $c->config->{view};
        my $app_key = $c->config->{app_key};
        my $create_stores_uri = $c->config->{create_stores_uri};

        my $stores_create = $taobao_oauth_url . "?response_type=" . $response_type . "&client_id=" . $app_key . "&redirect_uri=" . $create_stores_uri . "&scope=" . $scope . "&view=" . $view;

        my $renren_oauth = $c->config->{renren_oauth};
        my $renren_redirect_uri = $c->config->{renren_redirect_uri};
        my $renren_response_type = $c->config->{renren_response_type};
        my $renren_scope = $c->config->{renren_scope};
        my $renren_app_key = $c->config->{renren_app_key};

        my $renren_login = $renren_oauth . "?client_id=" . $renren_app_key . "&redirect_uri=" . $renren_redirect_uri . "&response_type=" . $renren_response_type;

	my $qq_app_id = $c->config->{qq_app_id};
        my $qq_app_key = $c->config->{qq_app_key};
        my $qq_redirect_url = $c->config->{qq_redirect_uri};
        my $qq_auth_url = $c->config->{qq_auth_uri};
        my $qq_login = $qq_auth_url."?response_type=code&client_id=".$qq_app_id."&redirect_uri=".$qq_redirect_url."&scope=all";

	$c->stash(renren_login => $renren_login);
	$c->stash(qq_login => $qq_login);
	$c->stash(stores_create => $stores_create);
	$c->stash(tuans_total => $tuan_total);
	$c->stash(stores_total => $stores_total);
	$c->stash(login_user => $c->session->{login_user});
	$c->stash(universities_list1 => $universities_list1);
	$c->stash(universities_list2 => $universities_list2);
        $c->stash(css => 'main_page.css');
        $c->stash(title => '拼单族 - 拼出好生活！');
        $c->stash(template => 'index.tt2');

}

sub stores_total:Local {
        my ($self, $c) = @_;
        $c->res->output($c->model('Store::StoreSearchModel')->store_search()->count);
}

sub stores_paging :Local {
        my ($self, $c) = @_;

        my $start_index = $c->request->params->{start_index};
        my $end_index = $c->request->params->{end_index};

        my $page = $start_index / 20;
        $page = $page + 1;
        my @stores = $c->model('Store::StoreSearchModel')->store_search($page);

#        $c->stash(
#                nowrapper => 1,
#                template => 'latest_stores.tt2',
#        	store_owners=> $c->model('UserStore::UserStoreModel')->get_store_owners(\@stores, $c),
#        	stores => \@stores
#	);

        $c->stash(
                nowrapper => 1,
                template => 'latest_stores.tt2',
        	stores => \@stores
	);
}

=head2 default

Standard 404 error page

=cut

sub default :Path {
	my ( $self, $c ) = @_;
	$c->response->status(404);
	$c->stash(css   => 'denglu.css');
	$c->stash(template => 'error.tt2');	    
	$c->clear_errors;
	$c->forward('render'); # trigger rendering 
}

=head2 auto

Check if there is a user and, if not, forward to login page

=cut

sub end : Private {
	my ( $self, $c ) = @_;

	$c->forward('render'); # trigger rendering 
	if ( scalar @{ $c->error } ) {
		$c->stash->{errors}   = $c->error;
		for my $error ( @{ $c->error } ) {
			$c->log->error($error);
		}
		$c->stash(css   => 'denglu.css');
		$c->stash(template => 'error.tt2');	    
		$c->clear_errors;
		$c->forward('render'); # trigger rendering 
	}
}


sub render : ActionClass('RenderView') {} 
=head1 AUTHOR

lijie,,,

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
